package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.SecondCategory;
import bean.TcImg;
import bean.ThirdCategory;
import common.BaseServlet;
import service.GoodsDAO;

/**
 * Servlet implementation class GoodsListServlet
 */
@WebServlet("/GoodsList")
public class GoodsListServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    GoodsDAO gdao=new GoodsDAO();
    private final int pagesize=2;//分页的单页数据条数
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GoodsListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    /*
     * 用保存在request中的搜索词在数据库中做模糊搜索，排序方式默认为4-热度降序
     * 默认查看页数为第一页，将搜索到的商品列表/排序方式/查看页数/总记录数存入request中并跳转到搜索商品结果页
     * */
    public String goodsListForSearch(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");

		PrintWriter out;
		out = response.getWriter();
		
		//判断排序方式，没有则默认为4-热度降序，并存入request中
		String sortStr=request.getParameter("sortWay");
		int sortWay=(sortStr==null)?4:Integer.parseInt(sortStr);
		request.setAttribute("sortWay", sortWay);
    	out.println("sortWay:"+sortWay);
		
    	
    	//获取要查看的页数并存入request中
		String viewStr=request.getParameter("viewPage");
		int viewPage=(viewStr==null)?1:Integer.parseInt(viewStr);
		request.setAttribute("currentPage", viewPage);
    	out.println("viewPage:"+viewPage);
    	//查询商品结果列表
    	List<ThirdCategory> list=new ArrayList<ThirdCategory>();
		
    	//获取搜索词并存入request中
    	String searchWord=request.getParameter("searchWord");
    	out.println("searchWord:"+searchWord);
    	request.setAttribute("searchWord", searchWord);
    	
		//模糊查询带关键字的商品信息，包括商品名/一级分类名称/二级分类名称/关键字
		list=gdao.queryBySearchWord(searchWord, sortWay, pagesize, viewPage);
		
		//获取总记录数并存入request中
		int listNum=gdao.queryBySearchWordNum(searchWord);
		out.println("listNum"+listNum);
		request.setAttribute("listNum", listNum);
		//步骤：1.根据second_category查找该id下所有的三级分类商品存入一个list集合中
		//2.根据三级商品的id到tc_img表下找到id对应的标题图片，与三级分类商品存入一个json字符串里
		//3.将json字符串里保存在request请求中，以及选择的二级分类id和三级分类id
		//将商品信息保存在json字符串里
		StringBuffer itemsList=new StringBuffer();
		itemsList.append("[");
		for(int i=0;i<list.size();i++) {
			ThirdCategory tc=list.get(i);
			itemsList.append("{\"name\":\""+tc.getName()+"\",");
			itemsList.append("\"price\":\""+tc.getPrice()+"\",");
			itemsList.append("\"discountMsg\":\""+tc.getDiscountMsg()+"\",");
			itemsList.append("\"label\":\""+tc.getLabel()+"\",");
			itemsList.append("\"evaluateNum\":\""+tc.getEvaluateNum()+"\",");
			int tcid=tc.getThirdCategoryid();
			itemsList.append("\"tcid\":\""+tcid+"\",");
			int scid=gdao.queryByTcid(tcid).get(0).getSecondCategoryid();
			int fcid=gdao.queryByScid(scid).get(0).getFirstCategoryid();
			itemsList.append("\"scid\":\""+scid+"\",");
			itemsList.append("\"fcid\":\""+fcid+"\",");
			String titleImg=gdao.queryTcImg(tcid).get(0).getTitleImg();
			if(i==list.size()-1) {
				itemsList.append("\"titleImg\":\""+titleImg+"\"}");
			}
			else {
				itemsList.append("\"titleImg\":\""+titleImg+"\"},");
			}
		}
		itemsList.append("]");
		request.setAttribute("items",new String(itemsList));
		return "f:jsp/GoodsListForSearch";
	}
    
    public String goodsListForClassify(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");

		PrintWriter out;
		out = response.getWriter();
		
		//判断排序方式，没有则默认为2-上架时间降序
		int sortWay=Integer.parseInt(request.getParameter("sortWay"));
		sortWay=(sortWay==-1)?2:sortWay;
		request.setAttribute("sortWay", sortWay);
		
		//将一级分类id和名字存入request中
		int selectFcid=Integer.parseInt(request.getParameter("fcid"));//一级分类id
    	String fcName=gdao.queryByFcid(selectFcid).get(0).getName();
		out.println("fcName:"+fcName);
    	request.setAttribute("fcName", fcName);
    	request.setAttribute("fcid", selectFcid);
    	
    	//根据选中的一级分类id将所有该分类下的二级分类名字和id存入数组字符串，并存入request中
    	StringBuffer scListsb=new StringBuffer();
    	scListsb.append("[");
    	List<SecondCategory> scList=gdao.queryScNameByFcid(selectFcid);
    	for(int i=0;i<scList.size();i++) {
        	scListsb.append("{\"scid\":\""+scList.get(i).getSecondCategoryid()+"\",");
    		if(i==scList.size()-1) {
            	scListsb.append("\"name\":\""+scList.get(i).getName()+"\"}");
    		}
    		else {
            	scListsb.append("\"name\":\""+scList.get(i).getName()+"\"},");
    		}
    	}
    	scListsb.append("]");
    	out.println(scListsb);
    	request.setAttribute("scList", scListsb);
    	
    	//获取要查看的页数
    	int viewPage=Integer.parseInt(request.getParameter("viewPage"));
    	viewPage=(viewPage==-1)?1:viewPage;
    	out.println("viewPage:"+viewPage);
    	request.setAttribute("currentPage", viewPage);
    	//查询商品结果列表
    	List<ThirdCategory> list=new ArrayList<ThirdCategory>();
    	//总记录数
    	int listNum;
		int selectScid=Integer.parseInt(request.getParameter("scid"));//二级分类id
		//判断是否选中一级分类id和二级分类id
		if(selectScid==-1) {
			//当仅选中一级分类id时查询所有该id下的三级分类商品，如选中手机时查询所有手机
			list=gdao.listFc(selectFcid,sortWay,pagesize,viewPage);
			request.setAttribute("scid", selectScid);
			//获取总记录数
			listNum=gdao.listFcNum(selectFcid);
	    	out.println("listNum:"+listNum);
		}
		else {
			out.println("selectScid:"+selectScid);
			//将二级分类id和名字存入request中
			String selectScName=gdao.queryByScid(selectScid).get(0).getName();
			out.print(selectScName);
			request.setAttribute("scName", selectScName);
			request.setAttribute("scid", selectScid);
			
			//当选中二级分类id时查询所有该id下的商品，如选中荣耀时查询所有荣耀系列手机
			list=gdao.listSc(selectScid,sortWay,pagesize,viewPage);
			//获取总记录数
			listNum=gdao.listScNum(selectScid);
		}
		out.println("listNum"+listNum);
		request.setAttribute("listNum", listNum);
		//步骤：1.根据second_category查找该id下所有的三级分类商品存入一个list集合中
		//2.根据三级商品的id到tc_img表下找到id对应的标题图片，与三级分类商品存入一个json字符串里
		//3.将json字符串里保存在request请求中，以及选择的二级分类id和三级分类id
		//将商品信息保存在json字符串里
		StringBuffer itemsList=new StringBuffer();
		itemsList.append("[");
		for(int i=0;i<list.size();i++) {
			ThirdCategory tc=list.get(i);
			itemsList.append("{\"name\":\""+tc.getName()+"\",");
			itemsList.append("\"price\":\""+tc.getPrice()+"\",");
			itemsList.append("\"discountMsg\":\""+tc.getDiscountMsg()+"\",");
			itemsList.append("\"label\":\""+tc.getLabel()+"\",");
			itemsList.append("\"evaluateNum\":\""+tc.getEvaluateNum()+"\",");
			int tcid=tc.getThirdCategoryid();
			itemsList.append("\"tcid\":\""+tcid+"\",");
			int scid=gdao.queryByTcid(tcid).get(0).getSecondCategoryid();
			int fcid=gdao.queryByScid(scid).get(0).getFirstCategoryid();
			itemsList.append("\"scid\":\""+scid+"\",");
			itemsList.append("\"fcid\":\""+fcid+"\",");
			String titleImg=gdao.queryTcImg(tcid).get(0).getTitleImg();
			if(i==list.size()-1) {
				itemsList.append("\"titleImg\":\""+titleImg+"\"}");
			}
			else {
				itemsList.append("\"titleImg\":\""+titleImg+"\"},");
			}
		}
		itemsList.append("]");
		request.setAttribute("items",new String(itemsList));
		return "f:jsp/GoodsListForClassify";
	}

	@Override
	public String basefun(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		return null;
	}

	

}
